package com.user.profile.service.label;

import com.alibaba.fastjson.JSON;
import com.user.profile.dao.LabelMapper;
import com.user.profile.entity.LabelEntity;
import com.user.profile.enums.OperateEnum;
import com.user.profile.request.SaveLabelRequest;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @Author linlx
 * @Date 2021/9/18 9:41
 * @Description
 **/
@Service
public class BuildCkManager {

  @Resource
  private UserAttributeCkBuildImpl userAttributeCkBuild;

  @Resource
  private UserBehaviorCkBuildImpl userBehaviorCkBuild;

  @Resource
  private LabelMapper labelMapper;

  public String buildCkQuery(Integer id) {
    LabelEntity labelEntity = labelMapper.selectById(id);
    if (null == labelEntity) {
      return StringUtils.EMPTY;
    }
    SaveLabelRequest request = JSON.parseObject(labelEntity.getJson(), SaveLabelRequest.class);
    // 拼接用户属性CK语句
    String userAttributeCkQuery = userAttributeCkBuild.buildCkQuery(request);
    // 拼接用户属性CK语句
    String userBehaviorCkQuery = userBehaviorCkBuild.buildCkQuery(request);
    // 单标签
    if (null == labelEntity.getParentOperate()) {
      // 其中有一个为 "";
      return userAttributeCkQuery + userBehaviorCkQuery;
    }
    StringBuilder result = new StringBuilder();
    // 同时含有用户属性和用户行为标签
    if (OperateEnum.AND.getCode().equals(labelEntity.getParentOperate())) {
      result.append("SELECT bitmapToArray(bitmapAnd");
    } else if (OperateEnum.OR.getCode().equals(labelEntity.getParentOperate())) {
      result.append("SELECT bitmapToArray(bitmapOr");
    }
    result.append("(user_number1, user_number2))")
        .append("FROM (")
        .append(userAttributeCkQuery)
        .append(" )")
        .append("A INNER JOIN (")
        .append(userBehaviorCkQuery)
        .append(") B ON B.BID = A.AID");
    return result.toString();
  }

}
